package org.budo.support.javax.servlet.filter.request.read.repeatable;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * @author lmw
 */
public class RepeatableReadRequestWrapper extends HttpServletRequestWrapper {
    private static final String REPEATABLE_READ_REQUEST_HEADER_NAMES_IN_ATTRIBUTE_KEY = "RepeatableReadRequestHeaderNamesInAttributeKey";

    public RepeatableReadRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    public Enumeration<String> getHeaderNames() {
        List<String> headerNameList = (List<String>) this.getAttribute(REPEATABLE_READ_REQUEST_HEADER_NAMES_IN_ATTRIBUTE_KEY);
        if (null == headerNameList) {
            headerNameList = new ArrayList<String>();
            Enumeration<String> enumeration = super.getHeaderNames();
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement();
                headerNameList.add(key);
            }
            this.setAttribute(REPEATABLE_READ_REQUEST_HEADER_NAMES_IN_ATTRIBUTE_KEY, headerNameList);
        }
        return Collections.enumeration(new ArrayList<String>(headerNameList));
    }

    public ServletInputStream getInputStream() throws IOException {
        return super.getInputStream();
    }

    public BufferedReader getReader() throws IOException {
        return super.getReader();
    }

    public String toString() {
        return super.toString() + ", wrapped(" + this.getRequest() + ")";
    }
}